import re

from apps.cbsp.models import *
from apps.common.common_func import checkIdcard
from apps.system.models import Region, Check
from extensions import serializers
from extensions.exceptions import ValidationError
from extensions.serializers import *
from apps.pbi.models import *
from apps.system.models import *
from datetime import timedelta, datetime
from django.utils import timezone

class CheckFlowSerializer(BaseSerializer):
    class RolesSerializer(BaseSerializer):
        class Meta:
            model = Role
            fields = ['id', 'name']
    check_flow_steps=RolesSerializer(
        source='steps', many=True, read_only=True, label='审批步骤')
    class Meta:
        model = CheckFlow
        fields = ['id', 'name','check_flow_steps']


class Cbsp_Bi_RecordsSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')
    employment_line_name = CharField(source='employment_line.name', read_only=True, label='用工条线')
    job_title_name = CharField(source='job_title.name', read_only=True, label='职名')
    job_level_name = CharField(source='job_level.name', read_only=True, label='职级')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records
        fields = '__all__'

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        instance = Cbsp_Bi_Records(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['status_name'] = '在岗' if representation['status'] else '离职'
        representation['is_core_name'] = '是' if representation['is_core'] else '否'
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        return representation


class Cbsp_Bi_RecordsImportSerializer(BaseSerializer):
    company = CharField(required=False,label='支撑服务单位名称')
    employee_number = CharField(required=False,label='员工编号')
    name = CharField(label='姓名')
    sfz_number = CharField(label='身份证号码')
    employment_line = CharField(required=False,label='用工条线')
    major = CharField(required=False, label='专业')
    department = CharField(required=False, label='部门（机构）名称')
    team = CharField(required=False, label='班组')
    grid = CharField(required=False,label='网格')
    job_title = CharField(required=False, label='职名')
    job_level = CharField(required=False, label='职级')
    status = CharField(required=False, label='人员状态')
    is_core = CharField(required=False, label='是否核心骨干岗位')
    job_date = DateTimeField(required=False, label='担任当前职位日期')
    personal_specialty = CharField(required=False, label='个人特长')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records
        fields = ['company', 'employee_number', 'name', 'sfz_number', 'employment_line', 'major', 'department', 'team',
                  'grid','job_title', 'job_level', 'status', 'is_core', 'job_date', 'personal_specialty', 'remark']


    # def validate_job_date(self, value):
    #     if isinstance(value, datetime):
    #         print('isinstance(value, datetime)')
    #         return value  # 如果 value 已经是 datetime.datetime 对象，不需要转换
    #
    #     # 尝试将日期字符串转换为 datetime.datetime 对象
    #     try:
    #         # 假设日期格式是 'YYYY-MM-DD'
    #         value_as_datetime = datetime.strptime(value, '%Y-%m-%d')
    #     except ValueError:
    #         # 如果转换失败，抛出 ValidationError
    #         raise serializers.ValidationError('日期格式无效，应为YYYY-MM-DD。')
    #
    #     # 返回转换后的 datetime.datetime 对象
    #     return value_as_datetime
    def validate_sfz_number(self, value):
        res =checkIdcard(value)
        if res != True:
            raise ValidationError(value+"身份证号码格式不对")
        return value


class Cbsp_Bi_Records_PersonnelSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    nation_name = CharField(source='nation.name', read_only=True, label='民族')
    marital_status_name = CharField(source='marital_status.name', read_only=True, label='婚姻状况')
    household_type_name = CharField(source='household_type.name', read_only=True, label='户口类别')
    health_status_name = CharField(source='health_status.name', read_only=True, label='健康状况')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Personnel
        fields = '__all__'

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Personnel(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.update_birthday_gender()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        #根据出生日期计算年龄
        # 根据出生日期计算年龄
        birthday = representation['birthday']
        birthday = datetime.strptime(birthday, "%Y-%m-%d")  # 将日期字符串转换为datetime对象
        if birthday:
            today = datetime.utcnow()
            age = today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day))
            representation['age'] = age
        else:
            representation['age'] = None
        representation['is_archiving_name'] = '是' if representation['is_archiving'] else '否'
        return representation


class Cbsp_Bi_Records_PersonnelImportSerializer(BaseSerializer):
    employee_number = CharField(required=False,label='员工编号')
    name = CharField(required=False,label='姓名')
    sfz_number = CharField(label='身份证号码')
    nation = CharField(required=False,label='民族')
    marital_status = CharField(required=False, label='婚姻状况')
    employment_cooperation = CharField(required=False, label='用工合作企业全称')
    native_place = CharField(required=False, label='籍贯')
    household_type = CharField(required=False,label='户口类别')
    household_address = CharField(required=False, label='户口所在地')
    is_archiving = CharField(required=False, label='是否为“建档立卡”人员')
    health_status = CharField(required=False, label='健康状况')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records_Personnel
        fields = ['employee_number', 'name', 'sfz_number', 'nation', 'marital_status', 'employment_cooperation',
                  'native_place', 'household_type', 'household_address', 'is_archiving', 'health_status', 'remark']


    # def validate_job_date(self, value):
    #     if isinstance(value, datetime):
    #         print('isinstance(value, datetime)')
    #         return value  # 如果 value 已经是 datetime.datetime 对象，不需要转换
    #
    #     # 尝试将日期字符串转换为 datetime.datetime 对象
    #     try:
    #         # 假设日期格式是 'YYYY-MM-DD'
    #         value_as_datetime = datetime.strptime(value, '%Y-%m-%d')
    #     except ValueError:
    #         # 如果转换失败，抛出 ValidationError
    #         raise serializers.ValidationError('日期格式无效，应为YYYY-MM-DD。')
    #
    #     # 返回转换后的 datetime.datetime 对象
    #     return value_as_datetime


class Cbsp_Bi_Records_ContactSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    emergency_contact_relationship_name = CharField(source='emergency_contact_relationship.name', read_only=True, label='紧急联系人关系')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Contact
        fields = '__all__'


    def validate_phone(self, value):
        res = re.match(r'1[3,4,5,7,8,9]\d{9}', value)
        if re.match(r'1[3,4,5,7,8,9]\d{9}',value) is None:
            raise ValidationError(value + '手机号码格式不对')
        return value


    def validate_emergency_contact_phone(self, value):
        res = re.match(r'1[3,4,5,7,8,9]\d{9}', value)
        if re.match(r'1[3,4,5,7,8,9]\d{9}',value) is None:
            raise ValidationError(value + '手机号码格式不对')
        return value

    #校验邮箱
    def validate_email(self, value):
        if re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$',value) is None:
            raise ValidationError(value + '邮箱格式不对')
        return value


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Contact(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')

        return representation


class Cbsp_Bi_Records_ContactImportSerializer(BaseSerializer):
    employee_number = CharField(required=False,label='员工编号')
    name = CharField(required=False,label='姓名')
    sfz_number = CharField(label='身份证号码')
    current_address = CharField(required=False,label='现居住地址')
    mailing_address = CharField(required=False, label='通信或邮寄地址')
    phone = CharField(required=False, label='联系电话')
    wechat = CharField(required=False, label='微信号')
    email = CharField(required=False, label='电子邮箱')
    emergency_contact_name = CharField(required=False,label='紧急联系人姓名')
    emergency_contact_relationship = CharField(required=False, label='紧急联系人关系')
    emergency_contact_phone = CharField(required=False, label='紧急联系人电话')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records_Contact
        fields = ['employee_number', 'name', 'sfz_number', 'current_address', 'mailing_address', 'phone', 'wechat','email',
                    'emergency_contact_name', 'emergency_contact_relationship', 'emergency_contact_phone', 'remark']


    def validate_phone(self, value):
        res = re.match(r'1[3,4,5,7,8,9]\d{9}', value)
        if re.match(r'1[3,4,5,7,8,9]\d{9}',value) is None:
            raise ValidationError(value + '手机号码格式不对')
        return value


    def validate_emergency_contact_phone(self, value):
        res = re.match(r'1[3,4,5,7,8,9]\d{9}', value)
        if re.match(r'1[3,4,5,7,8,9]\d{9}',value) is None:
            raise ValidationError(value + '手机号码格式不对')
        return value

    #校验邮箱
    def validate_email(self, value):
        if re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$',value) is None:
            raise ValidationError(value + '邮箱格式不对')
        return value


class Cbsp_Bi_Records_Commercial_InsuranceSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    insurance_type_name = CharField(source='insurance_type.name', read_only=True, label='险种类型')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Commercial_Insurance
        fields = '__all__'


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Commercial_Insurance(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')

        return representation


class Cbsp_Bi_Records_Commercial_InsuranceImportSerializer(BaseSerializer):
    employee_number = CharField(required=False,label='员工编号')
    name = CharField(required=False,label='姓名')
    sfz_number = CharField(label='身份证号码')
    insurance_type = CharField(required=False,label='险种类型')
    purchase_date = DateTimeField(required=False, label='购买时间')
    effective_date = DateTimeField(required=False, label='生效时间')
    expiration_date = DateTimeField(required=False, label='失效时间')
    insured_amount = FloatField(required=False, label='保额')
    underwriting_insurance_company_name = CharField(required=False, label='承保保险公司名称')
    insurance_agent_name = CharField(required=False, label='保险经办人姓名')
    insurance_reviewer_name = CharField(required=False,label='保险复核人姓名')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records_Commercial_Insurance
        fields = ['employee_number', 'name', 'sfz_number', 'insurance_type', 'purchase_date', 'effective_date',
                  'expiration_date', 'insured_amount', 'underwriting_insurance_company_name', 'insurance_agent_name',
                  'insurance_reviewer_name', 'remark']


class Cbsp_Bi_Records_Party_GroupSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    political_status_name = CharField(source='political_status.name', read_only=True, label='政治面貌')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Party_Group
        fields = '__all__'


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Party_Group(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        representation['is_democratic_party_name'] = '是' if representation['is_democratic_party'] else '否'
        join_party_group_date = instance.join_party_group_date
        representation['join_party_group_date_month'] = join_party_group_date.strftime(
            '%Y年%m月') if join_party_group_date else None
        return representation


class Cbsp_Bi_Records_Party_GroupImportSerializer(BaseSerializer):
    employee_number = CharField(required=False,label='员工编号')
    name = CharField(required=False,label='姓名')
    sfz_number = CharField(label='身份证号码')
    political_status = CharField(required=False,label='政治面貌')
    join_party_group_date = DateTimeField(required=False, label='加入党团组织年月')
    is_democratic_party = CharField(required=False, label='是否民主党派')
    democratic_party_name = CharField(required=False, label='民主党派名称')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records_Party_Group
        fields = ['employee_number', 'name', 'sfz_number', 'political_status', 'join_party_group_date',
                  'is_democratic_party', 'democratic_party_name', 'remark']


class Cbsp_Bi_Records_SkillSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    driving_license_type_name = CharField(source='driving_license_type.name', read_only=True, label='驾照类型')
    employment_line_name = CharField(source='employment_line.name', read_only=True, label='评定条线')
    star_rating_name = CharField(source='star_rating.name', read_only=True, label='星评等级')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Skill
        fields = '__all__'


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Skill(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        representation['is_driving_license_name'] = '是' if representation['is_driving_license'] else '否'
        representation['is_professional_driver_name'] = '是' if representation['is_professional_driver'] else '否'

        return representation


class Cbsp_Bi_Records_SkillImportSerializer(BaseSerializer):
    employee_number = CharField(required=False,label='员工编号')
    name = CharField(required=False,label='姓名')
    sfz_number = CharField(label='身份证号码')
    is_driving_license = CharField(required=False,label='是否有驾照')
    driving_license_type = CharField(required=False, label='驾照类型')
    driving_years = IntegerField(required=False, label='驾龄')
    is_professional_driver = CharField(required=False, label='是否专兼职驾驶员')
    employment_line = CharField(required=False, label='评定条线')
    star_rating = CharField(required=False, label='星评等级')
    effective_date = DateTimeField(required=False, label='生效时间')
    expiration_date = DateTimeField(required=False,label='失效时间')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records_Skill
        fields = ['employee_number', 'name', 'sfz_number',
                  'is_driving_license', 'driving_license_type', 'driving_years', 'is_professional_driver',
                    'employment_line', 'star_rating', 'effective_date', 'expiration_date', 'remark']


class Cbsp_Bi_Records_Personal_FinanceSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    medical_insurance_type_name = CharField(source='medical_insurance_type.name', read_only=True, label='医保类型')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Personal_Finance
        fields = '__all__'


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Personal_Finance(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        representation['is_medical_insurance_card_name'] = '是' if representation['is_medical_insurance_card'] else '否'

        return representation


class Cbsp_Bi_Records_Personal_FinanceImportSerializer(BaseSerializer):
    employee_number = CharField(required=False,label='员工编号')
    name = CharField(required=False,label='姓名')
    sfz_number = CharField(label='身份证号码')
    social_security_unit_name = CharField(required=False,label='社保缴纳单位名称')
    social_security_personal_account = CharField(required=False,label='社保个人账户')
    first_payment_of_social_security = DateTimeField(required=False, label='首次缴纳社保时间')
    provident_fund_unit_name = CharField(required=False,label='公积金缴纳单位名称')
    provident_fund_personal_account = CharField(required=False,label='公积金个人账户')
    first_payment_of_provident_fund = DateTimeField(required=False, label='首次缴纳公积金时间')
    medical_insurance_type = CharField(required=False,label='医保类型')
    first_payment_of_medical_insurance = DateTimeField(required=False, label='首次医保缴纳时间')
    is_medical_insurance_card = CharField(required=False,label='是否发放医保卡')
    bank_full_name = CharField(required=False,label='银行全称')
    branch_full_name = CharField(required=False,label='开户分/支行全称')
    card_number = CharField(required=False, label='卡号')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records_Personal_Finance
        fields = ['employee_number', 'name', 'sfz_number',
                  'social_security_unit_name', 'social_security_personal_account', 'first_payment_of_social_security',
                  'provident_fund_unit_name', 'provident_fund_personal_account', 'first_payment_of_provident_fund',
                  'medical_insurance_type', 'first_payment_of_medical_insurance', 'is_medical_insurance_card',
                  'bank_full_name', 'branch_full_name', 'card_number', 'remark']


class Cbsp_Bi_Records_EducationSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    highest_education_name = CharField(source='highest_education.name', read_only=True, label='最高学历')
    bachelor_degree_level_name = CharField(source='bachelor_degree_level.name', read_only=True, label='学位等级')
    highest_education_way_name = CharField(source='highest_education_way.name', read_only=True, label='最高学历获取方式')
    bachelor_degree_type_name = CharField(source='bachelor_degree_type.name', read_only=True, label='学位类型')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Education
        fields = '__all__'


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Education(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        representation['is_full_time_name'] = '是' if representation['is_full_time'] else '否'
        representation['is_education_verification_name'] = '是' if representation['is_education_verification'] else '否'
        representation['is_bachelor_degree_name'] = '是' if representation['is_bachelor_degree'] else '否'

        return representation


class Cbsp_Bi_Records_EducationImportSerializer(BaseSerializer):
    employee_number = CharField(required=False, label='员工编号')
    name = CharField(required=False, label='姓名')
    sfz_number = CharField(label='身份证号码')
    highest_education = CharField(required=False, label='最高学历')
    is_full_time = CharField(required=False, label='是否全日制')
    highest_education_way = CharField(required=False, label='最高学历获取方式')
    graduate_school = CharField(required=False, label='毕业院校')
    graduate_date = DateTimeField(required=False, label='毕业年月')
    major = CharField(required=False, label='专业')
    education_certificate_number = CharField(required=False, label='学历证书编号（或毕业证书编号）')
    is_education_verification = CharField(required=False, label='学历是否验证')
    verification_date = DateTimeField(required=False, label='验证时间')
    verification_person = CharField(required=False, label='验证人')
    is_bachelor_degree = CharField(required=False, label='是否有学士学位证书')
    bachelor_degree_level = CharField(required=False, label='学位等级')
    bachelor_degree_date = CharField(required=False, label='获取学士学位证书时间')
    bachelor_degree_number = CharField(required=False, label='学位证书编号')
    bachelor_degree_type = CharField(required=False, label='学位类型')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records_Education
        fields = ['employee_number', 'name', 'sfz_number',
                  'highest_education', 'is_full_time', 'highest_education_way',
                  'graduate_school', 'graduate_date', 'major',
                  'education_certificate_number', 'is_education_verification',
                  'verification_date', 'verification_person', 'is_bachelor_degree',
                  'bachelor_degree_level', 'bachelor_degree_date', 'bachelor_degree_number', 'bachelor_degree_type',
                  'remark']


class Cbsp_Bi_Records_WorkSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    employment_source_name = CharField(source='employment_source.name', read_only=True, label='用工来源')
    full_part_time_driver_safety_officer_name = CharField(source='full_part_time_driver_safety_officer.name', read_only=True, label='专兼职驾驶员/安全员情况')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Work
        fields = '__all__'


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Work(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        is_items = ['is_entry_training', 'is_entry_training_assessment', 'is_full_time', 'on_job_status',
                    'is_entry_physical_examination',
                    'is_full_part_time', 'is_resignation_procedures', 'is_labor_social_security_notice'
                    ]
        for is_item in is_items:
            if is_item == 'on_job_status':
                representation[is_item+'_name'] = '在职' if representation[is_item]  else '离职'
            else:
                representation[is_item+'_name'] = '是' if representation[is_item]  else '否'

        #根据首次服务铁通时间服务计算铁通工作年限
        first_service_date = representation['first_service_date']
        # first_service_date = datetime.strptime(first_service_date, "%Y-%m-%d")  # 将日期字符串转换为datetime对象
        if first_service_date:
            first_service_date = datetime.strptime(first_service_date, "%Y-%m-%d")  # 将日期字符串转换为datetime对象
            today = datetime.utcnow()
            service_years = today.year - first_service_date.year - ((today.month, today.day) < (first_service_date.month, first_service_date.day))
            representation['service_years'] = service_years
        else:
            representation['service_years'] = None

        return representation


class Cbsp_Bi_Records_WorkImportSerializer(BaseSerializer):
    employee_number = CharField(required=False, label='员工编号')
    name = CharField(required=False, label='姓名')
    sfz_number = CharField(label='身份证号码')
    employment_source = CharField(required=False, label='用工来源')
    is_entry_training = CharField(required=False, label='是否参加入职培训')
    is_entry_training_assessment = CharField(required=False, label='是否通过入职培训考核')
    is_full_time = CharField(required=False, label='是否全职')
    on_job_status = CharField(required=False, label='在职状态')
    first_work_date = DateTimeField(required=False, label='首次参加工作时间')
    first_service_date = DateTimeField(required=False, label='首次服务铁通时间')
    is_entry_physical_examination = CharField(required=False, label='是否入职体检')
    positive_date = DateTimeField(required=False, label='转正时间')
    # service_years = IntegerField(required=False, label='服务铁通工作年限')
    current_contract_start_date = DateTimeField(required=False, label='现劳动合同起始时间')
    current_contract_end_date = DateTimeField(required=False, label='现劳动合同终止时间')
    employment_cooperation_enterprise = CharField(required=False, label='用工合作企业全称')
    is_full_part_time = CharField(required=False, label='是否专兼职')
    full_part_time_driver_safety_officer = CharField(required=False, label='专兼职驾驶员/安全员情况')
    is_resignation_procedures = CharField(required=False, label='是否办理离职手续')
    resignation_date = DateTimeField(required=False, label='离职时间')
    resignation_reason = CharField(required=False, label='离职原因')
    is_labor_social_security_notice = CharField(required=False, label='是否成功发放“劳动关系和社保缴纳告知书”')
    remark = CharField(required=False, label='备注')

    class Meta:
        model = Cbsp_Bi_Records_Work
        fields = ['employee_number', 'name', 'sfz_number', 'employment_source',
                  'is_entry_training', 'is_entry_training_assessment', 'is_full_time',
                  'on_job_status', 'first_work_date', 'first_service_date',
                  'is_entry_physical_examination', 'positive_date',
                  # 'service_years',
                  'current_contract_start_date', 'current_contract_end_date',
                  'employment_cooperation_enterprise', 'is_full_part_time',
                  'full_part_time_driver_safety_officer', 'is_resignation_procedures',
                  'resignation_date', 'resignation_reason', 'is_labor_social_security_notice','remark']


class Cbsp_Bi_Records_CertificateSerializer(BaseSerializer):
    company_name = CharField(source='cbsp_bi.company.name', read_only=True, label='公司')
    employee_number = CharField(source='cbsp_bi.employee_number', read_only=True, label='员工编号')
    name = CharField(source='cbsp_bi.name', read_only=True, label='姓名')
    sfz_number = CharField(source='cbsp_bi.sfz_number', read_only=True, label='身份证号码')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Cbsp_Bi_Records_Certificate
        fields = '__all__'


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        instance = Cbsp_Bi_Records_Certificate(**validated_data)
        instance.id = instance.generate_unique_id()
        instance.save()
        return instance
        # return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        representation['is_electrician_certificate_name'] = '是' if representation['is_electrician_certificate'] else '否'
        representation['is_high_altitude_certificate_name'] = '是' if representation['is_high_altitude_certificate'] else '否'
        representation['is_line_certificate_name'] = '是' if representation['is_line_certificate'] else '否'
        representation['is_review_electrician_certificate_name'] = '是' if representation['is_review_electrician_certificate'] else '否'
        representation['is_review_high_altitude_certificate_name'] = '是' if representation['is_review_high_altitude_certificate'] else '否'
        representation['is_review_line_certificate_name'] = '是' if representation['is_review_line_certificate'] else '否'
        representation['is_mobile_maintenance_qualification_certification_name'] = '是' if representation['is_mobile_maintenance_qualification_certification'] else '否'

        return representation


class Cbsp_Bi_Records_CertificateImportSerializer(BaseSerializer):
    employee_number = CharField(required=False, label='员工编号')
    name = CharField(required=False, label='姓名')
    sfz_number = CharField(label='身份证号码')
    is_electrician_certificate = CharField(required=False, label='是否持有电工证')
    electrician_certificate_issuing_authority = CharField(required=False, label='电工证发证机关')
    electrician_certificate_acquisition_date = DateTimeField(required=False, label='电工证取证日期')
    electrician_certificate_validity_period = DateTimeField(required=False, label='电工证截止有效期')
    electrician_certificate_number = CharField(required=False, label='电工证证书编号')
    is_review_electrician_certificate = CharField(required=False, label='是否复审')
    is_high_altitude_certificate = CharField(required=False, label='是否持有登高证')
    high_altitude_certificate_issuing_authority = CharField(required=False, label='登高证发证机关')
    high_altitude_certificate_acquisition_date = DateTimeField(required=False, label='登高证取证日期')
    high_altitude_certificate_validity_period = DateTimeField(required=False, label='登高证截止有效期')
    high_altitude_certificate_number = CharField(required=False, label='登高证证书编号')
    is_review_high_altitude_certificate = CharField(required=False, label='是否复审')
    is_line_certificate = CharField(required=False, label='是否持有线务证')
    line_certificate_issuing_authority = CharField(required=False, label='线务证发证机关')
    line_certificate_acquisition_date = DateTimeField(required=False, label='线务证取证日期')
    line_certificate_validity_period = DateTimeField(required=False, label='线务证截止有效期')
    line_certificate_number = CharField(required=False, label='线务证证书编号')
    is_review_line_certificate = CharField(required=False, label='是否复审')
    is_mobile_maintenance_qualification_certification = CharField(required=False, label='是否通过移动代维资格认证')
    mobile_maintenance_qualification_certification_level = CharField(required=False, label='移动代维资格认证等级')
    mobile_maintenance_qualification_certification_major = CharField(required=False, label='移动代维资格认证专业')
    mobile_maintenance_qualification_certification_sub_major = CharField(required=False, label='移动代维资格认证子专业')
    mobile_maintenance_qualification_certification_issuing_date = DateTimeField(required=False, label='移动代维资格认证签发日期')
    mobile_maintenance_qualification_certification_validity_period = DateTimeField(required=False, label='移动代维资格认证有效时间')
    other_important_certificate_name = CharField(required=False, label='其他重要证书名称')
    other_important_certificate_issuing_authority = CharField(required=False, label='发证机关')
    other_important_certificate_acquisition_date = DateTimeField(required=False, label='取证日期')
    other_important_certificate_validity_period = DateTimeField(required=False, label='证书截止有效期')
    other_important_certificate_number = CharField(required=False, label='证书编号')

    class Meta:
        model = Cbsp_Bi_Records_Certificate
        fields = ['employee_number', 'name', 'sfz_number', 'is_electrician_certificate',
                  'electrician_certificate_issuing_authority', 'electrician_certificate_acquisition_date',
                  'electrician_certificate_validity_period', 'electrician_certificate_number',
                  'is_review_electrician_certificate', 'is_high_altitude_certificate',
                  'high_altitude_certificate_issuing_authority', 'high_altitude_certificate_acquisition_date',
                  'high_altitude_certificate_validity_period', 'high_altitude_certificate_number',
                  'is_review_high_altitude_certificate', 'is_line_certificate',
                  'line_certificate_issuing_authority', 'line_certificate_acquisition_date',
                  'line_certificate_validity_period', 'line_certificate_number',
                  'is_review_line_certificate', 'is_mobile_maintenance_qualification_certification',
                  'mobile_maintenance_qualification_certification_level',
                  'mobile_maintenance_qualification_certification_major',
                  'mobile_maintenance_qualification_certification_sub_major',
                  'mobile_maintenance_qualification_certification_issuing_date',
                  'mobile_maintenance_qualification_certification_validity_period',
                  'other_important_certificate_name', 'other_important_certificate_issuing_authority',
                  'other_important_certificate_acquisition_date',
                  'other_important_certificate_validity_period', 'other_important_certificate_number']
